package client

import (
	"chatting/model"
	"encoding/json"
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/data/validation"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"time"
)

func (la *LocalApp) BuildChatWindow(friendName string) fyne.Window {
	window := la.app.NewWindow(localUser.Username + "和" + friendName + "的聊天")

	la.chatWindow[friendName] = window

	list := la.chatList[friendName]

	listWithData := widget.NewListWithData(list,
		func() fyne.CanvasObject {
			text := widget.NewRichTextWithText("")
			text.Resize(fyne.NewSize(text.Size().Width, 2*text.Size().Height))
			return text
		},
		func(item binding.DataItem, object fyne.CanvasObject) {
			bytes := item.(binding.Bytes)
			obj := object.(*widget.RichText)

			msg := new(model.ResChatMessage)

			get, err := bytes.Get()
			if err != nil {
				panic(err)
			}

			err = json.Unmarshal(get, msg)
			if err != nil {
				panic(err)
			}

			text := widget.NewRichTextWithText(msg.Time.Format("15:04:05") + "   " + msg.MessageFrom + ":\n" + msg.Data)
			obj.Segments = text.Segments
			obj.Wrapping = text.Wrapping
		},
	)

	entry := widget.NewMultiLineEntry()
	entry.Validator = validation.NewRegexp("^[\\s\\S]*.*[^\\s][\\s\\S]*$", "请输入发送内容")
	getFunc := GetFunc(func() {
		m := new(model.ChatMessage)
		m.FromUser = localUser.Username
		m.ToUser = friendName
		m.Data = entry.Text
		m.Time = time.Now()

		la.client.sendChan <- m
	})
	button := widget.NewButton("发送", getFunc)

	border := container.NewBorder(nil, button, nil, nil, entry)

	mainC := container.NewVSplit(listWithData, border)

	window.SetContent(mainC)
	return window
}

//GhatListen 在登录后才启用
func (la *LocalApp) GhatListen() {
	for {
		select {
		case msg := <-la.client.receiveChan:
			fmt.Println("??????")
			switch msg.Typeis() {
			case model.ChatRes:
				chatMessage := msg.(*model.ResChatMessage)
				chatMessage.Time = time.Now()
				if chatMessage.Data == "好友不在线" {
					//fmt.Println("好友不在线消息来自于", chatMessage.MessageFrom, chatMessage.Data)
					dialog.ShowInformation("提示", "好友不在线", la.chatWindow[chatMessage.MessageFrom])
					continue
				}
				bytes := chatMessage.Bytes()
				//log.Println("收到聊天消息", chatMessage)
				if chatMessage.MessageFrom == localUser.Username { //是自己发的消息
					la.chatList[chatMessage.MessageTo].Append(bytes)
					continue
				} else { //是别人发来的消息
					la.chatList[chatMessage.MessageFrom].Append(bytes)
				}

				fmt.Println("我是", localUser.Username)
				fmt.Println("chatMessage.MessageFrom data", chatMessage.MessageFrom, chatMessage.Data)

			default:
				panic("收到了不该存在的消息")
			}
		}
	}
}

func GetFunc(f func()) func() {
	return f
}
